

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="dayu">
  <meta name="keywords" content="">
  
    <meta name="description" content="VueX（Vue 状态管理模式)一、初识 VueX1.1 关于VueXVueX是适用于在Vue项目开发时使用的状态管理工具。试想一下，如果在一个项目开发中频繁的使用组件传参的方式来同步data中的值，一旦项目变得很庞大，管理和维护这些值将是相当棘手的工作。为此，Vue为这些被多个组件频繁使用的值提供了一个统一管理的工具——VueX。在具有VueX的 Vue 项目中，我们只需要把这些值定义在 Vue">
<meta property="og:type" content="article">
<meta property="og:title" content="Vuex">
<meta property="og:url" content="http://example.com/2022/10/15/Vuex/index.html">
<meta property="og:site_name" content="Dayu">
<meta property="og:description" content="VueX（Vue 状态管理模式)一、初识 VueX1.1 关于VueXVueX是适用于在Vue项目开发时使用的状态管理工具。试想一下，如果在一个项目开发中频繁的使用组件传参的方式来同步data中的值，一旦项目变得很庞大，管理和维护这些值将是相当棘手的工作。为此，Vue为这些被多个组件频繁使用的值提供了一个统一管理的工具——VueX。在具有VueX的 Vue 项目中，我们只需要把这些值定义在 Vue">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-10-15T10:04:00.000Z">
<meta property="article:modified_time" content="2023-09-05T13:21:06.365Z">
<meta property="article:author" content="dayu">
<meta property="article:tag" content="vuex">
<meta name="twitter:card" content="summary_large_image">
  
  
  
  <title>Vuex - Dayu</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.3","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 5.4.2"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>dayu</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Vuex"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-10-15 18:04" pubdate>
          2022年10月15日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          5.3k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          45 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Vuex</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="VueX（Vue-状态管理模式"><a href="#VueX（Vue-状态管理模式" class="headerlink" title="VueX（Vue 状态管理模式)"></a>VueX（Vue 状态管理模式)</h1><h2 id="一、初识-VueX"><a href="#一、初识-VueX" class="headerlink" title="一、初识 VueX"></a>一、初识 VueX</h2><h3 id="1-1-关于VueX"><a href="#1-1-关于VueX" class="headerlink" title="1.1 关于VueX"></a>1.1 关于<code>VueX</code></h3><p><code>VueX</code>是适用于在<code>Vue</code>项目开发时使用的状态管理工具。试想一下，如果在一个项目开发中频繁的使用组件传参的方式来同步<code>data</code>中的值，一旦项目变得很庞大，管理和维护这些值将是相当棘手的工作。为此，<code>Vue</code>为这些被多个组件频繁使用的值提供了一个统一管理的工具——<code>VueX</code>。在具有<code>VueX</code>的 Vue 项目中，我们只需要把这些值定义在 VueX 中，即可在整个 Vue 项目的组件中使用。</p>
<h3 id="1-2-安装"><a href="#1-2-安装" class="headerlink" title="1.2 安装"></a>1.2 安装</h3><ul>
<li>Npm 安装 Vuex</li>
</ul>
<figure class="highlight coffeescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs coffeescript"><span class="hljs-built_in">npm</span> i vuex -s<br></code></pre></td></tr></table></figure>

<ul>
<li>在项目的根目录下新增一个<code>store</code>文件夹，在该文件夹内创建 index.js</li>
</ul>
<h3 id="1-3-使用"><a href="#1-3-使用" class="headerlink" title="1.3 使用"></a>1.3 使用</h3><h4 id="1-3-1-初始化store下index-js中的内容"><a href="#1-3-1-初始化store下index-js中的内容" class="headerlink" title="1.3.1 初始化store下index.js中的内容"></a>1.3.1 初始化<code>store</code>下<code>index.js</code>中的内容</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> <span class="hljs-title class_">Vue</span> <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span><br><span class="hljs-keyword">import</span> <span class="hljs-title class_">Vuex</span> <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vuex&#x27;</span><br><br><span class="hljs-comment">//挂载Vuex</span><br><span class="hljs-title class_">Vue</span>.<span class="hljs-title function_">use</span>(<span class="hljs-title class_">Vuex</span>)<br><br><span class="hljs-comment">//创建VueX对象</span><br><span class="hljs-keyword">const</span> store = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Vuex</span>.<span class="hljs-title class_">Store</span>(&#123;<br>  <span class="hljs-attr">state</span>: &#123;<br>    <span class="hljs-comment">//存放的键值对就是所要管理的状态</span><br>    <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;helloVueX&#x27;</span>,<br>  &#125;,<br>&#125;)<br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> store<br></code></pre></td></tr></table></figure>

<h4 id="1-3-2-将-store-挂载到当前项目的-Vue-实例当中去"><a href="#1-3-2-将-store-挂载到当前项目的-Vue-实例当中去" class="headerlink" title="1.3.2 将 store 挂载到当前项目的 Vue 实例当中去"></a>1.3.2 将 store 挂载到当前项目的 Vue 实例当中去</h4><p>打开 main.js</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> <span class="hljs-title class_">Vue</span> <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span><br><span class="hljs-keyword">import</span> <span class="hljs-title class_">App</span> <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./App&#x27;</span><br><span class="hljs-keyword">import</span> router <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./router&#x27;</span><br><span class="hljs-keyword">import</span> store <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./store&#x27;</span><br><br><span class="hljs-title class_">Vue</span>.<span class="hljs-property">config</span>.<span class="hljs-property">productionTip</span> = <span class="hljs-literal">false</span><br><br><span class="hljs-comment">/* eslint-disable no-new */</span><br><span class="hljs-keyword">new</span> <span class="hljs-title class_">Vue</span>(&#123;<br>  <span class="hljs-attr">el</span>: <span class="hljs-string">&#x27;#app&#x27;</span>,<br>  router,<br>  store, <span class="hljs-comment">//store:store 和router一样，将我们创建的Vuex实例挂载到这个vue实例中</span><br>  <span class="hljs-attr">render</span>: <span class="hljs-function">(<span class="hljs-params">h</span>) =&gt;</span> <span class="hljs-title function_">h</span>(<span class="hljs-title class_">App</span>),<br>&#125;)<br></code></pre></td></tr></table></figure>

<h4 id="1-3-3-在组件中使用-Vuex"><a href="#1-3-3-在组件中使用-Vuex" class="headerlink" title="1.3.3 在组件中使用 Vuex"></a>1.3.3 在组件中使用 Vuex</h4><p>例如在 App.vue 中，我们要将 state 中定义的 name 拿来在 h1 标签中显示</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;template&gt;<br>  &lt;div id=&quot;app&quot;&gt;<br>    name:<br>    &lt;h1&gt;&#123;&#123; $store.state.name &#125;&#125;&lt;/h1&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br></code></pre></td></tr></table></figure>

<p>或者要在组件方法中使用</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs vue">methods:&#123; add()&#123; console.log(this.$store.state.name) &#125; &#125;,<br></code></pre></td></tr></table></figure>

<p><strong>注意，请不要在此处更改<code>state</code>中的状态的值</strong></p>
<h3 id="1-4-安装-Vue-开发工具-VueDevtools"><a href="#1-4-安装-Vue-开发工具-VueDevtools" class="headerlink" title="1.4 安装 Vue 开发工具 VueDevtools"></a>1.4 安装 Vue 开发工具 VueDevtools</h3><p>在 Vue 项目开发中，需要监控项目中得各种值，为了提高效率，Vue 提供了一款浏览器扩展——VueDevtools。</p>
<h2 id="二、VueX-中的核心内容"><a href="#二、VueX-中的核心内容" class="headerlink" title="二、VueX 中的核心内容"></a>二、VueX 中的核心内容</h2><p>在 VueX 对象中，其实不止有<code>state</code>,还有用来操作<code>state</code>中数据的方法集，以及当我们需要对<code>state</code>中的数据需要加工的方法集等等成员。</p>
<p>成员列表：</p>
<ul>
<li>state 存放状态</li>
<li>mutations state 成员操作</li>
<li>getters 加工 state 成员给外界</li>
<li>actions 异步操作</li>
<li>modules 模块化状态管理</li>
</ul>
<h3 id="2-1-VueX-的工作流程"><a href="#2-1-VueX-的工作流程" class="headerlink" title="2.1 VueX 的工作流程"></a>2.1 VueX 的工作流程</h3><p>首先，<code>Vue</code>组件如果调用某个<code>VueX</code>的方法过程中需要向后端请求时或者说出现异步操作时，需要<code>dispatch</code> VueX 中<code>actions</code>的方法，以保证数据的同步。可以说，<code>action</code>的存在就是为了让<code>mutations</code>中的方法能在异步操作中起作用。</p>
<p>如果没有异步操作，那么我们就可以直接在组件内提交状态中的<code>Mutations</code>中自己编写的方法来达成对<code>state</code>成员的操作。注意，之前有提到，不建议在组件中直接对<code>state</code>中的成员进行操作，这是因为直接修改(例如：<code>this.$store.state.name = &#39;hello&#39;</code>)的话不能被<code>VueDevtools</code>所监控到。</p>
<p>最后被修改后的 state 成员会被渲染到组件的原位置当中去。</p>
<h3 id="2-2-Mutations"><a href="#2-2-Mutations" class="headerlink" title="2.2 Mutations"></a>2.2 Mutations</h3><p><code>mutations</code>是操作<code>state</code>数据的方法的集合，比如对该数据的修改、增加、删除等等。</p>
<h4 id="2-2-1-Mutations-使用方法"><a href="#2-2-1-Mutations-使用方法" class="headerlink" title="2.2.1 Mutations 使用方法"></a>2.2.1 Mutations 使用方法</h4><p><code>mutations</code>方法都有默认的形参：</p>
<p>(<strong>[state]</strong> <strong>[,payload]</strong>)</p>
<ul>
<li><code>state</code>是当前<code>VueX</code>对象中的<code>state</code></li>
<li><code>payload</code>是该方法在被调用时传递参数使用的</li>
</ul>
<p>例如，我们编写一个方法，当被执行时，能把下例中的 name 值修改为<code>&quot;jack&quot;</code>,我们只需要这样做</p>
<p><code>index.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">import</span> <span class="hljs-title class_">Vue</span> <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span><br><span class="hljs-keyword">import</span> <span class="hljs-title class_">Vuex</span> <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vuex&#x27;</span><br><br><span class="hljs-title class_">Vue</span>.<span class="hljs-title function_">use</span>(<span class="hljs-title class_">Vuex</span>)<br><br><span class="hljs-keyword">const</span> store = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Vuex</span>.<span class="hljs-title function_">store</span>(&#123;<br>  <span class="hljs-attr">state</span>: &#123;<br>    <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;helloVueX&#x27;</span>,<br>  &#125;,<br>  <span class="hljs-attr">mutations</span>: &#123;<br>    <span class="hljs-comment">//es6语法，等同edit:funcion()&#123;...&#125;</span><br>    <span class="hljs-title function_">edit</span>(<span class="hljs-params">state</span>) &#123;<br>      state.<span class="hljs-property">name</span> = <span class="hljs-string">&#x27;jack&#x27;</span><br>    &#125;,<br>  &#125;,<br>&#125;)<br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> store<br></code></pre></td></tr></table></figure>

<p>而在组件中，我们需要这样去调用这个<code>mutation</code>——例如在 App.vue 的某个<code>method</code>中:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-variable language_">this</span>.<span class="hljs-property">$store</span>.<span class="hljs-title function_">commit</span>(<span class="hljs-string">&#x27;edit&#x27;</span>)<br></code></pre></td></tr></table></figure>

<h4 id="2-2-2-Mutation-传值"><a href="#2-2-2-Mutation-传值" class="headerlink" title="2.2.2 Mutation 传值"></a>2.2.2 Mutation 传值</h4><p>在实际生产过程中，会遇到需要在提交某个<code>mutation</code>时需要携带一些参数给方法使用。</p>
<p>单个值提交时:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-variable language_">this</span>.<span class="hljs-property">$store</span>.<span class="hljs-title function_">commit</span>(<span class="hljs-string">&#x27;edit&#x27;</span>, <span class="hljs-number">15</span>)<br></code></pre></td></tr></table></figure>

<p>当需要多参提交时，推荐把他们放在一个对象中来提交:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-variable language_">this</span>.<span class="hljs-property">$store</span>.<span class="hljs-title function_">commit</span>(<span class="hljs-string">&#x27;edit&#x27;</span>, &#123; <span class="hljs-attr">age</span>: <span class="hljs-number">15</span>, <span class="hljs-attr">sex</span>: <span class="hljs-string">&#x27;男&#x27;</span> &#125;)<br></code></pre></td></tr></table></figure>

<p>接收挂载的参数：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-title function_">edit</span>(<span class="hljs-params">state,payload</span>)&#123;<br>    state.<span class="hljs-property">name</span> = <span class="hljs-string">&#x27;jack&#x27;</span><br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(payload) <span class="hljs-comment">// 15或&#123;age:15,sex:&#x27;男&#x27;&#125;</span><br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>另一种提交方式</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-variable language_">this</span>.<span class="hljs-property">$store</span>.<span class="hljs-title function_">commit</span>(&#123;<br>  <span class="hljs-attr">type</span>: <span class="hljs-string">&#x27;edit&#x27;</span>,<br>  <span class="hljs-attr">payload</span>: &#123;<br>    <span class="hljs-attr">age</span>: <span class="hljs-number">15</span>,<br>    <span class="hljs-attr">sex</span>: <span class="hljs-string">&#x27;男&#x27;</span>,<br>  &#125;,<br>&#125;)<br></code></pre></td></tr></table></figure>

<h4 id="2-2-3-增删-state-中的成员"><a href="#2-2-3-增删-state-中的成员" class="headerlink" title="2.2.3 增删 state 中的成员"></a>2.2.3 增删 state 中的成员</h4><p>为了配合 Vue 的响应式数据，我们在 Mutations 的方法中，应当使用 Vue 提供的方法来进行操作。如果使用<code>delete</code>或者<code>xx.xx = xx</code>的形式去删或增，则 Vue 不能对数据进行实时响应。</p>
<ul>
<li><p>Vue.set 为某个对象设置成员的值，若不存在则新增</p>
<p>例如对 state 对象中添加一个 age 成员</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-title class_">Vue</span>.<span class="hljs-title function_">set</span>(state, <span class="hljs-string">&#x27;age&#x27;</span>, <span class="hljs-number">15</span>)<br></code></pre></td></tr></table></figure></li>
<li><p>Vue.delete 删除成员</p>
<p>将刚刚添加的 age 成员删除</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-title class_">Vue</span>.<span class="hljs-title function_">delete</span>(state, <span class="hljs-string">&#x27;age&#x27;</span>)<br></code></pre></td></tr></table></figure></li>
</ul>
<h3 id="2-3-Getters"><a href="#2-3-Getters" class="headerlink" title="2.3 Getters"></a>2.3 Getters</h3><p>可以对 state 中的成员加工后传递给外界</p>
<p>Getters 中的方法有两个默认参数</p>
<ul>
<li>state 当前 VueX 对象中的状态对象</li>
<li>getters 当前 getters 对象，用于将 getters 下的其他 getter 拿来用</li>
</ul>
<p>例如</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-attr">getters</span>:&#123;<br>    <span class="hljs-title function_">nameInfo</span>(<span class="hljs-params">state</span>)&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;姓名:&quot;</span>+state.<span class="hljs-property">name</span><br>    &#125;,<br>    <span class="hljs-title function_">fullInfo</span>(<span class="hljs-params">state,getters</span>)&#123;<br>        <span class="hljs-keyword">return</span> getters.<span class="hljs-property">nameInfo</span>+<span class="hljs-string">&#x27;年龄:&#x27;</span>+state.<span class="hljs-property">age</span><br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>组件中调用</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-variable language_">this</span>.<span class="hljs-property">$store</span>.<span class="hljs-property">getters</span>.<span class="hljs-property">fullInfo</span><br></code></pre></td></tr></table></figure>

<h3 id="2-4-Actions"><a href="#2-4-Actions" class="headerlink" title="2.4 Actions"></a>2.4 Actions</h3><p>由于直接在<code>mutation</code>方法中进行异步操作，将会引起数据失效。所以提供了 Actions 来专门进行异步操作，最终提交<code>mutation</code>方法。</p>
<p><code>Actions</code>中的方法有两个默认参数</p>
<ul>
<li><code>context</code> 上下文(相当于箭头函数中的 this)对象</li>
<li><code>payload</code> 挂载参数</li>
</ul>
<p>例如，我们在两秒中后执行<code>2.2.2</code>节中的<code>edit</code>方法</p>
<p>由于<code>setTimeout</code>是异步操作，所以需要使用<code>actions</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-attr">actions</span>:&#123;<br>    <span class="hljs-title function_">aEdit</span>(<span class="hljs-params">context,payload</span>)&#123;<br>        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>            context.<span class="hljs-title function_">commit</span>(<span class="hljs-string">&#x27;edit&#x27;</span>,payload)<br>        &#125;,<span class="hljs-number">2000</span>)<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>在组件中调用:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-variable language_">this</span>.<span class="hljs-property">$store</span>.<span class="hljs-title function_">dispatch</span>(<span class="hljs-string">&#x27;aEdit&#x27;</span>, &#123; <span class="hljs-attr">age</span>: <span class="hljs-number">15</span> &#125;)<br></code></pre></td></tr></table></figure>

<p><strong>改进:</strong></p>
<p>由于是异步操作，所以我们可以为我们的异步操作封装为一个<code>Promise</code>对象</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-title function_">aEdit</span>(<span class="hljs-params">context,payload</span>)&#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve,reject</span>)=&gt;</span>&#123;<br>        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">()=&gt;</span>&#123;<br>            context.<span class="hljs-title function_">commit</span>(<span class="hljs-string">&#x27;edit&#x27;</span>,payload)<br>            <span class="hljs-title function_">resolve</span>()<br>        &#125;,<span class="hljs-number">2000</span>)<br>    &#125;)<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="2-5-modules"><a href="#2-5-modules" class="headerlink" title="2.5 modules"></a>2.5 modules</h3><p>当项目庞大，状态非常多时，可以采用模块化管理模式。Vuex 允许我们将 store 分割成<strong>模块（module）</strong>。每个模块拥有自己的 <code>state、mutation、action、getter</code>、甚至是嵌套子模块——从上至下进行同样方式的分割。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-attr">modules</span>:&#123;<br>    <span class="hljs-attr">a</span>:&#123;<br>        <span class="hljs-attr">state</span>:&#123;&#125;,<br>        <span class="hljs-attr">getters</span>:&#123;&#125;,<br>        ....<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>组件内调用模块 a 的状态：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-variable language_">this</span>.<span class="hljs-property">$store</span>.<span class="hljs-property">state</span>.<span class="hljs-property">a</span><br></code></pre></td></tr></table></figure>

<p>而提交或者<code>dispatch</code>某个方法和以前一样,会自动执行所有模块内的对应<code>type</code>的方法：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-variable language_">this</span>.<span class="hljs-property">$store</span>.<span class="hljs-title function_">commit</span>(<span class="hljs-string">&#x27;editKey&#x27;</span>)<br><span class="hljs-variable language_">this</span>.<span class="hljs-property">$store</span>.<span class="hljs-title function_">dispatch</span>(<span class="hljs-string">&#x27;aEditKey&#x27;</span>)<br></code></pre></td></tr></table></figure>

<h4 id="2-5-1-模块的细节"><a href="#2-5-1-模块的细节" class="headerlink" title="2.5.1 模块的细节"></a>2.5.1 模块的细节</h4><ul>
<li><p>模块中<code>mutations</code>和<code>getters</code>中的方法接受的第一个参数是自身局部模块内部的<code>state</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-attr">modules</span>:&#123;<br>    <span class="hljs-attr">a</span>:&#123;<br>        <span class="hljs-attr">state</span>:&#123;<span class="hljs-attr">key</span>:<span class="hljs-number">5</span>&#125;,<br>        <span class="hljs-attr">mutations</span>:&#123;<br>            <span class="hljs-title function_">editKey</span>(<span class="hljs-params">state</span>)&#123;<br>                state.<span class="hljs-property">key</span> = <span class="hljs-number">9</span><br>            &#125;<br>        &#125;,<br>        ....<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure></li>
<li><p><code>getters</code>中方法的第三个参数是根节点状态</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-attr">modules</span>:&#123;<br>    <span class="hljs-attr">a</span>:&#123;<br>        <span class="hljs-attr">state</span>:&#123;<span class="hljs-attr">key</span>:<span class="hljs-number">5</span>&#125;,<br>        <span class="hljs-attr">getters</span>:&#123;<br>            <span class="hljs-title function_">getKeyCount</span>(<span class="hljs-params">state,getter,rootState</span>)&#123;<br>                <span class="hljs-keyword">return</span>  rootState.<span class="hljs-property">key</span> + state.<span class="hljs-property">key</span><br>            &#125;<br>        &#125;,<br>        ....<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure></li>
<li><p><code>actions</code>中方法获取局部模块状态是<code>context.state</code>,根节点状态是<code>context.rootState</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-attr">modules</span>:&#123;<br>    <span class="hljs-attr">a</span>:&#123;<br>        <span class="hljs-attr">state</span>:&#123;<span class="hljs-attr">key</span>:<span class="hljs-number">5</span>&#125;,<br>        <span class="hljs-attr">actions</span>:&#123;<br>            <span class="hljs-title function_">aEidtKey</span>(<span class="hljs-params">context</span>)&#123;<br>                <span class="hljs-keyword">if</span>(context.<span class="hljs-property">state</span>.<span class="hljs-property">key</span> === context.<span class="hljs-property">rootState</span>.<span class="hljs-property">key</span>)&#123;<br>                    context.<span class="hljs-title function_">commit</span>(<span class="hljs-string">&#x27;editKey&#x27;</span>)<br>                &#125;<br>            &#125;<br>        &#125;,<br>        ....<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="三、规范目录结构"><a href="#三、规范目录结构" class="headerlink" title="三、规范目录结构"></a>三、规范目录结构</h2><p>如果把整个<code>store</code>都放在<code>index.js</code>中是不合理的，所以需要拆分。比较合适的目录格式如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs shell">store:.<br>│  actions.js<br>│  getters.js<br>│  index.js<br>│  mutations.js<br>│  mutations_type.js   ##该项为存放mutaions方法常量的文件，按需要可加入<br>│<br>└─modules<br>        Astore.js<br></code></pre></td></tr></table></figure>

<p>对应的内容存放在对应的文件中，和以前一样，在<code>index.js</code>中存放并导出<code>store</code>。<code>state</code>中的数据尽量放在<code>index.js</code>中。而<code>modules</code>中的<code>Astore</code>局部模块状态如果多的话也可以进行细分。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/vue/" class="category-chain-item">vue</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/vuex/">#vuex</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Vuex</div>
      <div>http://example.com/2022/10/15/Vuex/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>dayu</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年10月15日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/10/15/hexo-gitee%E6%90%AD%E5%BB%BA%E4%B8%AA%E4%BA%BA%E5%8D%9A%E5%AE%A2/" title="hexo+gitee搭建个人博客">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">hexo+gitee搭建个人博客</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
